//
//  HHInputAuthorCodeViewController.m
//  HHBroker
//
//  Created by He Wei on 9/17/15.
//  Copyright © 2015 harry. All rights reserved.
//

#import "HHInputAuthorCodeViewController.h"
#import "HHTimerButton.h"
#import "HttpRequestManager.h"
#import "NSString+ValidateArgument.h"
#import "HHInputPropertyViewController.h"
#import "HHApplyServiceViewController.h"

@interface HHInputAuthorCodeViewController () <UITextFieldDelegate>
{
    HHTimerButton *_timerButton;
    BOOL _returnButtonEnable;
}

@property (nonatomic, strong) UIView *lineView;
@property (nonatomic, strong) HHTimerButton *timerButton;
@property (nonatomic, copy) NSString *authorCode;
@property (nonatomic, weak) IBOutlet UIView *codeView;
@property (nonatomic, weak) IBOutlet UILabel *phoneLabel;
@property (nonatomic, weak) IBOutlet UIButton *returnButton;
@property (nonatomic, weak) IBOutlet UITextField *authorCodeTextField;

@end

@implementation HHInputAuthorCodeViewController
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        self.title = NSLocalizedString(@"注册", nil);
    }
    return self;
}

#pragma mark - Life Cycle

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];


}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    [self.codeView addSubview:self.lineView];
    [self.codeView addSubview:self.timerButton];
    NSString *phone = [self.readAuthorCodePhone stringByReplacingCharactersInRange:NSMakeRange(4, 4) withString:@"****"];
    self.phoneLabel.text = phone;

}


#pragma mark - Delegate

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
    if ([string isEqualToString:@"\n"]) {
        if (_returnButtonEnable) {
            [self returnAuthorCodeButtonClicked:self.returnButton];
            [textField resignFirstResponder];
        }
        return NO;
    }
    return YES;

}


#pragma mark - 
#pragma mark - Event Response
- (IBAction)textFieldValueChanged:(UITextField *)textField
{
    _returnButtonEnable = textField.text.length > 0 ? YES : NO;
    self.returnButton.enabled = _returnButtonEnable;

}

- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
{
    [super touchesBegan:touches withEvent:event];
    [self.view endEditing:YES];
}

- (void)timeButtonClicked:(HHTimerButton *)button
{

    [self.view endEditing:YES];
    button.timeOut = 60;
    
    __block MBProgressHUD *hub = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    hub.mode = MBProgressHUDModeIndeterminate;
    hub.labelText = NSLocalizedString(@"正在获取验证码", nil);;
    // network request
    // add suciety code
    NSString *encPhone = self.readAuthorCodePhone;
    NSString *urlString = [NSString stringWithFormat:@"%@&mobile=%@",KUrlGetCode, encPhone];
    [HttpRequestManager getWithUrlString:urlString success:^(id response) {
        NSInteger code = [[response objectForKey:@"code"] integerValue];
        if (code == 1) {
            // sent success
            UIImageView *imageView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"alert_success"]];
            hub.mode = MBProgressHUDModeCustomView;
            hub.customView = imageView;
            hub.labelText = NSLocalizedString(@"发送成功，请查看手机短信", nil);;
            hub.completionBlock = ^ {
                [self.authorCodeTextField becomeFirstResponder];
            };
            [hub hide:YES afterDelay:1];
        }
        else {
            NSString *msgString = [response objectForKey:@"msg"];
            hub.mode = MBProgressHUDModeText;
            hub.labelText = msgString;
            [hub hide:YES afterDelay:2];
        }
    } failure:^(NSError *error){
        [hub hide:YES];
        hub.mode = MBProgressHUDModeText;
        hub.labelText = NSLocalizedString(@"网络好像有点问题", nil);
        [hub hide:YES afterDelay:1];
        
        
    } isLogin:NO];

}

- (IBAction)returnAuthorCodeButtonClicked:(UIButton *)sender
{
    [self.view endEditing:YES];
    NSString *authorCode = self.authorCodeTextField.text;
    authorCode = [authorCode stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];
    if (![NSString validateAuthorCode:authorCode]) {
        UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:nil message:@
        "验证码不正确，请重新输入" delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
        [alertView show];
        return;
    }
//测试跳转
    HHInputPropertyViewController *inputPVC = [[HHInputPropertyViewController alloc] init];
    inputPVC.phone = self.readAuthorCodePhone;
    [self.navigationController pushViewController:inputPVC animated:YES];
    return;
    
    
    //验证验证码
    __block MBProgressHUD *hub = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    hub.mode = MBProgressHUDModeIndeterminate;
    
    //网络请求
    //加入加密字段
    NSString *encPhone = self.readAuthorCodePhone;
    NSString *urlString = [NSString stringWithFormat:@"%@&mobile=%@&code=%@", KUrlVerifyCode, encPhone, authorCode];
    
    [HttpRequestManager getWithUrlString:urlString success:^(id response) {
        NSInteger code = [[response objectForKey:@"code"] integerValue];
        if (code == 1) {
            //验证通过
            [hub hide:NO];
            HHInputPropertyViewController *inputPVC = [[HHInputPropertyViewController alloc] init];
            inputPVC.phone = self.readAuthorCodePhone;
            [self.navigationController pushViewController:inputPVC animated:YES];
        } else {
            NSString *msgString = [response objectForKey:@"msg"];
            hub.mode = MBProgressHUDModeText;
            hub.labelText = msgString;
            [hub hide:YES afterDelay:2];
        }
    
    } failure:^(NSError *error) {
        NSString *msgString = @"网络好像有问题";
        hub.mode = MBProgressHUDModeText;
        hub.labelText = msgString;
        [hub hide:YES afterDelay:2];
    } isLogin:NO];
}

#pragma mark - Setter && Getter

- (UIView *)lineView
{
    if (_lineView == nil) {
        float ispandingX;
        if (DEVICE_IS_IPHONE4 || DEVICE_IS_IPHONE5 || kWidth <= 320) {
            ispandingX = 110;
        } else {
            ispandingX = 130;
        }
        _lineView = [[UIView alloc] initWithFrame:CGRectMake(self.view.frame.size.width-(ispandingX+10), 7, 0.5, 30)];
        _lineView.autoresizingMask = UIViewAutoresizingFlexibleWidth|UIViewAutoresizingFlexibleLeftMargin;
        _lineView.backgroundColor = UIColorFromRGB(0xe3e3e3);
        
    }
    return _lineView;
}

- (HHTimerButton *)timerButton
{
    if (_timerButton == nil) {
        float ispandingX;
        if (DEVICE_IS_IPHONE4 || DEVICE_IS_IPHONE5|| kWidth <= 320) {
            ispandingX = 110;
        } else {
            ispandingX = 130;
        
        }
        _timerButton = [HHTimerButton buttonWithType:UIButtonTypeCustom];
        _timerButton.frame = CGRectMake(self.view.frame.size.width-(ispandingX+5), 7, ispandingX, 30);
        [_timerButton setTitle:NSLocalizedString(@"重发验证码", nil) forState:UIControlStateNormal];
        [_timerButton setTitleColor:UIColorFromRGB(0x3b3b3b) forState:UIControlStateNormal];
        _timerButton.contentHorizontalAlignment = UIControlContentHorizontalAlignmentCenter;
        _timerButton.titleLabel.font = kJiaYuanFontWithSize(15.0f);
        _timerButton.autoresizingMask = UIViewAutoresizingFlexibleLeftMargin;
        _timerButton.timeOut = 60;
        [_timerButton addTarget:self action:@selector(timeButtonClicked:) forControlEvents:UIControlEventTouchUpInside];
    }
    return _timerButton;
}



/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
